"""
@Author    : ghenyar
@Time      : 2025/8/28 16:27
@File      : login
@Desc      :
"""
from datetime import datetime

from fastapi import APIRouter, Request, Depends
from sqlalchemy.ext.asyncio import AsyncSession

from app.admin.decorator import log_operation
from app.admin.schemas.login import LoginSchemas
from app.admin.service.admin_service import AdminService
from app.admin.service.menu_service import MenuService
from app.admin.service.role_service import RoleService
from app.common.exception.exceptions import BusinessException
from app.common.response import ApiResponse
from app.common.tools import verify_password
from app.core.db import async_get_db
from app.libs.captcha import Captcha
from app.utils.jwt import JWTUtils

from app.utils.redisCache import RedisCache

router = APIRouter()

@router.post("/login", response_model=ApiResponse)
@log_operation(types=0)
async def do_login(login_data: LoginSchemas,
                   request: Request,
                   db: AsyncSession = Depends(async_get_db)):
    """
    后台登录
    :param login_data: 登录所需参数
    :param request: 请求体
    :param db: 数据库会话
    :return: 登录成功后返回相关数据
    """

    # 判断验证码
    captcha_key = "captcha_" + login_data.captcha_key
    redis_cache = RedisCache()
    has_captcha = await redis_cache.has(captcha_key)
    if not has_captcha:
        return ApiResponse.failed("验证码无效、请刷新验证码后再试输入")

    verify = await redis_cache.get(captcha_key)
    if verify["value"].upper() != login_data.captcha.upper():
        return ApiResponse.failed("验证码错误、请输入正确的验证码")

    # 根据登录账号查询管理员信息
    admin_service = AdminService()
    admin = await admin_service.get_admin_by_account(db, login_data.username)
    if not admin:
        return ApiResponse.failed("当前账号不存在、请确认账号或密码是否有误")

    # 判断登录密码正确
    if not verify_password(login_data.password, admin.password):
        return ApiResponse.failed("账号或密码错误、请确认后再次登录")
    if admin.is_locked == 1:
        return ApiResponse.failed("当前账号已锁定、请联系管理员进行解锁")

    # 登录成功后生成token
    jwt_token = JWTUtils.generate_token({'id': admin.id, 'username': admin.account})
    jwt_expire = JWTUtils.get_token_expired(jwt_token)

    # 获取当前账号的权限
    role_permissions = None
    if admin.is_super != 1:
        # 根据角色获取权限
        role = await admin_service.get_admin_role(db, admin.id)
        role_permissions = await RoleService.get_role_permissions_by_role_ids(db,role) if role else None
    # 获取权限数据
    auth_menu, auth_code = await MenuService.get_permission_auth_login(db, role_permissions)

    # 登录成功给前端返回的数据
    login_data = {
        "id": f"AID{admin.id:06}",
        "account": admin.account,
        "nickname": admin.nickname,
        "avatar": admin.avatar,
        "token": jwt_token,
        "expire_time": jwt_expire * 1000,
        "authorities": auth_code,
        "menus": auth_menu,
    }

    await admin_service.update_admin_dict(db,admin.id, {"last_login": datetime.now()})

    key = f"login_{admin.id}"  # login_1
    await RedisCache.set(key=key, value=login_data)

    # 登录成功从redis中释放验证码数据
    await redis_cache.delete(captcha_key)
    return ApiResponse.result(login_data, '登录成功')


@router.get("/captcha", response_model=ApiResponse)
async def get_captcha(request: Request):
    """
    获取登录页验证码
    :return: 验证码
    """
    captcha = Captcha()
    captcha_data = captcha.generate_captcha()
    redis_captcha = {'key': captcha_data.get('captcha_key'), 'value': captcha_data.get('captcha_value')}
    # 检查redis
    cache = RedisCache()
    connecting = await cache.check_connection()
    if not connecting:
        raise BusinessException(message="服务器连接失败！，请和管理员联系", code=500)
    await cache.set("captcha_" + captcha_data.get('captcha_key'), redis_captcha, expire=300)
    return ApiResponse.result({'captcha': captcha_data.get('captcha'), 'captcha_key': captcha_data.get('captcha_key')})
